package com.geeksaga.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author newbie
 * @since 0.1
 */
public class BundleConvert {
	private static final String JDBC_DRIVER = "";
	private static final String DB_URL = "";
	private static final String DB_USERID = "";
	private static final String DB_PASSWD = "";

	private static final String LOCALE_KO = "ko";
	private static final String LOCALE_EN = "en";

	private static final String FILE_PATH = "C:\\";

	private static final String COMPANY_MULT_LANG_TYPE = "U05703";

	private static final String COMPANY_BUNDLE_FILE = FILE_PATH + "company.properties";
	private static final String COMPANY_BUNDLE_FILE_EN = FILE_PATH + "company_en.properties";

	private static final String COMMON_BUNDLE_FILE = FILE_PATH + "code.properties";
	private static final String COMMON_BUNDLE_FILE_EN = FILE_PATH + "code_en.properties";

	private static final String COMMON_BUNDLE_CODE_FILE = FILE_PATH + "code_ko";
	private static final String COMMON_BUNDLE_CODE_FILE_EN = FILE_PATH + "code_en";

	private static final String COMMON_BUNDLE_JS_FILE = FILE_PATH + "code_ko.js";
	private static final String COMMON_BUNDLE_JS_FILE_EN = FILE_PATH + "code_en.js";

	private Connection con;

	private Connection getConnection() {
		try {
			if (con == null || con.isClosed()) {
				Class.forName(JDBC_DRIVER);
				con = DriverManager.getConnection(DB_URL, DB_USERID, DB_PASSWD);
				System.out.println("acquire()...");
			}

			return con;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	private void selectCA202M(String locale, String type, String fileName) {
		StringBuilder query = new StringBuilder();
		query.append("\nSELECT B.MULT_LANG_ID AS multLangId");
		query.append("\n           , B.MULT_LANG_VAL AS multLangVal");
		query.append("\n   FROM AF.CA202M A");
		query.append("\n           , AF.CA213M B");
		query.append("\n WHERE A.COMPANY_MULT_LANG_ID = B.MULT_LANG_ID");
		query.append("\n      AND B.LOCALE = ?");
		query.append("\n      AND B.MULT_LANG_TYPE = ?");

		selectTemplate(query.toString(), locale, type, fileName);
	}

	private void selectCA018C(String locale, String fileName) {
		StringBuilder query = new StringBuilder();
		query.append("\nSELECT A.MAJ_CODE AS majCode");
		query.append("\n           , A.RESC_KEY AS multLangId");
		query.append("\n           , A.SUB_CODE_VAL AS multLangVal");
		query.append("\n           , A.LOW_MAJ_CODE AS lowMajCode");
		query.append("\n   FROM AF.CA018C A");
		query.append("\n WHERE A.USE_INDC = '1'");
		query.append("\n      AND A.LOCALE = ?");
		query.append("\n      AND A.LOW_MAJ_CODE IS NULL");
		query.append("\n ORDER BY A.MAJ_CODE, MULTLANGID");

		selectTemplate(query.toString(), locale, fileName, false);
	}

	private void selectCA018CLowMajCode(String locale, String fileName) {
		StringBuilder query = new StringBuilder();
		query.append("\nSELECT A.MAJ_CODE AS majCode");
		query.append("\n           , A.RESC_KEY AS multLangId");
		query.append("\n           , A.SUB_CODE_VAL AS multLangVal");
		query.append("\n           , A.LOW_MAJ_CODE AS lowMajCode");
		query.append("\n   FROM AF.CA018C A");
		query.append("\n WHERE A.USE_INDC = '1'");
		query.append("\n      AND A.LOCALE = ?");
		query.append("\n      AND A.LOW_MAJ_CODE IS NOT NULL");
		query.append("\n ORDER BY A.MAJ_CODE, MULTLANGID");

		selectTemplate(query.toString(), locale, fileName, true);
	}

	private void selectTemplate(String query, String locale, String type, String fileName) {
		PreparedStatement pstmt = null;
		Connection con = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			System.out.println(query.toString());
			pstmt = con.prepareStatement(query.toString());
			pstmt.setString(1, locale);
			pstmt.setString(2, type);

			rs = pstmt.executeQuery();

			makeResourceBundle(rs, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
					pstmt = null;
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.setAutoCommit(true);
					con.close();
					con = null;
				} catch (Exception e) {
				}
			if (rs != null)
				try {
					rs.close();
					rs = null;
				} catch (Exception e) {
				}
		}
	}

	private void selectTemplate(String query, String locale, String fileName, boolean isLowCode) {
		PreparedStatement pstmt = null;
		Connection con = null;
		ResultSet rs = null;

		try {
			con = getConnection();

			System.out.println(query.toString());
			pstmt = con.prepareStatement(query.toString());
			pstmt.setString(1, locale);

			rs = pstmt.executeQuery();

			if (isLowCode) {
				makeJs2(rs, fileName);
			} else {
				makeJs(rs, fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pstmt != null)
				try {
					pstmt.close();
					pstmt = null;
				} catch (Exception e) {
				}
			if (con != null)
				try {
					con.setAutoCommit(true);
					con.close();
					con = null;
				} catch (Exception e) {
				}
			if (rs != null)
				try {
					rs.close();
					rs = null;
				} catch (Exception e) {
				}
		}
	}

	public void makeResourceBundle(ResultSet rs, String fileName) {
		BufferedWriter out = null;

		try {
			out = new BufferedWriter(new FileWriter(new File(fileName)));

			int i = 0;
			while (rs.next()) {
				System.out.println((i++) + " cnt - " + rs.getString("multLangId") + " = "
						+ getAscii(rs.getString("multLangVal")));
				out.write(rs.getString("multLangId") + " = " + getAscii(rs.getString("multLangVal")) + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
				}
		}
	}

	public void makeJs(ResultSet rs, String fileName) {
		String template = "C:\\WorkSpace\\workspace\\uware\\WebContent\\common\\template\\code.template";

		BufferedReader in = null;
		BufferedWriter out = null;

		try {
			in = new BufferedReader(new FileReader(new File(template)));
			out = new BufferedWriter(new FileWriter(new File(fileName)));

			String line = "";
			while ((line = in.readLine()) != null) {
				System.out.println(line);

				if ("__REPLACE_CODE_CASE__".equals(line.trim())) {
					String preMajCode = null;
					boolean isFirst = true;

					while (rs.next()) {
						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") == null) { // && !isFirst) {
							out.write("\t\t\t\t\tthis.codeMaster.set('" + preMajCode + "', codes); \r\n");
							out.write("\t\t\t\t\tthis.keyset.push('" + preMajCode + "'); \r\n");
							out.write("\t\t\t\t\tbreak; \r\n");
							out.write("\r\n");
						}

						if (preMajCode == null || !preMajCode.equals(rs.getString("majCode"))) {
							out.write("\t\t\t\tcase '" + rs.getString("majCode") + "' : \r\n");
							out.write("\t\t\t\t\tcodes = new Hash(); \r\n");
						}

						// if(preMajCode != null && preMajCode.equals(rs.getString("majCode"))) {
						out.write("\t\t\t\t\tcodes.set('" + rs.getString("multLangId") + "', '"
								+ rs.getString("multLangVal") + "'); \r\n");
						// }

						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") != null && !isFirst) {
							out.write("\t\t\t\t\tbreak; \r\n");
						}

						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") != null) {
							isFirst = false;
						}

						preMajCode = rs.getString("majCode");
					}

					out.write("\t\t\t\t\tthis.codeMaster.set('" + preMajCode + "', codes); \r\n");
					out.write("\t\t\t\t\tthis.keyset.push('" + preMajCode + "'); \r\n");
					out.write("\t\t\t\t\tbreak; \r\n");
					out.write("\r\n");
				} else {
					out.write(line + "\r\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
				}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
				}
		}
	}

	public void makeJs2(ResultSet rs, String fileName) {
		// String template = "C:\\WorkSpace\\workspace\\uware\\WebContent\\common\\template\\code.template";
		String template = null;

		if (COMMON_BUNDLE_JS_FILE.equals(fileName)) {
			template = COMMON_BUNDLE_CODE_FILE;
		} else if (COMMON_BUNDLE_JS_FILE_EN.equals(fileName)) {
			template = COMMON_BUNDLE_CODE_FILE_EN;
		}

		BufferedReader in = null;
		BufferedWriter out = null;

		try {
			in = new BufferedReader(new FileReader(new File(template)));
			out = new BufferedWriter(new FileWriter(new File(fileName)));

			String line = "";
			while ((line = in.readLine()) != null) {
				System.out.println(line);

				if ("__REPLACE_LOW_CODE_CASE__".equals(line.trim())) {
					String preMajCode = null;
					boolean isFirst = true;

					while (rs.next()) {
						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") == null) { // && !isFirst) {
							out.write("\t\t\t\t\tthis.codeMaster.set('" + preMajCode + "', codes); \r\n");
							out.write("\t\t\t\t\tthis.keyset.push('" + preMajCode + "'); \r\n");
							out.write("\t\t\t\t\tthis.linkedCodeMaster.set('" + preMajCode + "', codesLinked); \r\n");
							out.write("\t\t\t\t\tthis.linkedKeyset.push('" + preMajCode + "'); \r\n");
							out.write("\t\t\t\t\tbreak; \r\n");
							out.write("\r\n");
						}

						if (preMajCode == null || !preMajCode.equals(rs.getString("majCode"))) {
							out.write("\t\t\t\tcase '" + rs.getString("majCode") + "' : \r\n");
							out.write("\t\t\t\t\tcodes = new Hash(); \r\n");
							out.write("\t\t\t\t\tcodesLinked = new Hash(); \r\n");
						}

						out.write("\t\t\t\t\tcodes.set('" + rs.getString("multLangId") + "', '"
								+ rs.getString("multLangVal") + "'); \r\n");
						out.write("\t\t\t\t\tcodesLinked.set('" + rs.getString("multLangId") + "', '"
								+ rs.getString("lowMajCode") + "'); \r\n");

						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") != null && !isFirst) {
							out.write("\t\t\t\t\tbreak; \r\n");
						}

						if (preMajCode != null && !preMajCode.equals(rs.getString("majCode"))
								&& rs.getString("lowMajCode") != null) {
							isFirst = false;
						}

						preMajCode = rs.getString("majCode");
					}

					if (preMajCode != null) {
						out.write("\t\t\t\t\tthis.codeMaster.set('" + preMajCode + "', codes); \r\n");
						out.write("\t\t\t\t\tthis.keyset.push('" + preMajCode + "'); \r\n");
						out.write("\t\t\t\t\tthis.linkedCodeMaster.set('" + preMajCode + "', codesLinked); \r\n");
						out.write("\t\t\t\t\tthis.linkedKeyset.push('" + preMajCode + "'); \r\n");
						out.write("\t\t\t\t\tbreak; \r\n");
						out.write("\r\n");
					}
				} else {
					out.write(line + "\r\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
				}
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
				}
		}
	}

	public static void main(String args[]) throws Exception {
		long t1 = System.currentTimeMillis();
		BundleConvert convert = new BundleConvert();
		convert.selectCA202M(LOCALE_KO, COMPANY_MULT_LANG_TYPE, COMPANY_BUNDLE_FILE);
		convert.selectCA202M(LOCALE_EN, COMPANY_MULT_LANG_TYPE, COMPANY_BUNDLE_FILE_EN);

		convert.selectCA018C(LOCALE_KO, COMMON_BUNDLE_FILE);
		convert.selectCA018C(LOCALE_EN, COMMON_BUNDLE_FILE_EN);

		convert.selectCA018C(LOCALE_KO, COMMON_BUNDLE_CODE_FILE);
		convert.selectCA018C(LOCALE_EN, COMMON_BUNDLE_CODE_FILE_EN);

		convert.selectCA018CLowMajCode(LOCALE_KO, COMMON_BUNDLE_JS_FILE);
		convert.selectCA018CLowMajCode(LOCALE_EN, COMMON_BUNDLE_JS_FILE_EN);

		long t2 = System.currentTimeMillis();
		System.out.println((t2 - t1));
	}

	private static CharSequence getAscii(CharSequence cs) {
		if (cs == null) {
			return "";
		}

		int len = cs.length();
		String tmp = null;
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < len; i++) {
			tmp = Integer.toHexString(cs.charAt(i));
			sb.append("\\u");
			sb.append((tmp.length() == 4 ? tmp : "00" + tmp));
		}

		return sb.toString();
	}

	public static String readEncodedFile(InputStream is, String charset) throws IOException {
		BufferedReader br = null;
		InputStreamReader isr = null;
		StringBuffer buf = new StringBuffer();

		try {
			if (charset == null || charset.length() == 0) {
				isr = new InputStreamReader(is);
			} else {
				isr = new InputStreamReader(is, charset);
			}

			br = new BufferedReader(isr);

			for (String sLine = br.readLine(); sLine != null; sLine = br.readLine()) {
				buf.append(sLine).append("\n");
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (UnsupportedEncodingException e) {
			throw e;
		} finally {
			if (br != null)
				br.close();
			if (isr != null)
				isr.close();
		}

		return buf.toString();
	}
}